import Vue from "vue";
import Vuex from "vuex";

import user from "./user";

Vue.use(Vuex); //vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
  strict: true,
  state: {
    cartList: uni.getStorageSync("cartList") || [],
  },
  getters: {
    isAllSelected(state) {
      return state.cartList.every((item) => item.goods_select);
    },
    selectedCartList(state) {
      return state.cartList.filter((item) => item.goods_select);
    },
    selectedCartListCount(state, getters) {
      // forEach的实现方式 便于理解
      // let sum = 0;
      // getters.selectedCartList.forEach((item) => {
      //   sum += item.goods_count;
      // });
      // return sum;

      // reduce实现方式
      return getters.selectedCartList.reduce((sum, current) => {
        return (sum += current.goods_count);
      }, 0);
    },
    selectedCartListPrice(state, getters) {
      // reduce实现方式
      return getters.selectedCartList.reduce((sum, current) => {
        return (sum += current.goods_count * current.goods_price);
      }, 0);
    },
  },
  mutations: {
    updateCartList(state, payload) {
      state.cartList = payload;
      uni.setStorageSync("cartList", payload);
    },
  },
  modules: {
    user,
  },
});
export default store;
